package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.atguigu.tingshu.common.constant.SystemConstant.ORDER_STATUS_CANCEL;
import static com.atguigu.tingshu.common.constant.SystemConstant.ORDER_STATUS_PAID;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        Long userId = AuthContextHolder.getUserId();
        //1.根据订单编号查询本地交易记录，判断状态，如果有则直接返回
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.如果本地交易记录不存在，则构建交易记录，保存到数据库中
        paymentInfo = new PaymentInfo();
        //2.1处理支付类型为：订单  封装本地交易记录内容、金额。
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.1.1 根据订单编号远程调用订单服务获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在");

            //2.1.2 判断订单状态，如果订单是已支付 或 已取消 抛出异常终止业务
            String orderStatus = orderInfo.getOrderStatus();
            if (ORDER_STATUS_PAID.equals(orderStatus) || ORDER_STATUS_CANCEL.equals(orderStatus)) {
                throw new RuntimeException("订单已支付或已取消");
            }
            //2.1.3 封装本地交易记录内容、金额。
            paymentInfo.setContent("订单：" + orderInfo.getOrderTitle());
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setPayWay(orderInfo.getPayWay());
        }

        //2.2 处理支付类型为：充值  封装本地交易记录内容、金额。
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.2.1 根据充值订单编号远程调用账户服务获取订单信息
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值订单不存在");

            //2.2.2 判断充值状态，如果订单是已支付 或 已取消 抛出异常终止业务
            String rechargeStatus = rechargeInfo.getRechargeStatus();
            if (ORDER_STATUS_PAID.equals(rechargeStatus) || ORDER_STATUS_CANCEL.equals(rechargeStatus)) {
                throw new RuntimeException("充值订单已支付或已取消");
            }
            //2.2.3 封装本地交易记录内容、金额。
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount());
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setPayWay(rechargeInfo.getPayWay());
        }
        //2.3 封装其他字段
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //TODO 其他字段 微信交易号，回调时间，回调内容 需要等用户付款成功后，商户系统收到微信回调再去更新
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();
        //2.4 保存本地交易记录
        this.save(paymentInfo);
        return paymentInfo;
    }

    /**
     * 处理本地交易记录以及对应订单或者充值业务
     *
     * @param transaction 微信回调交易对象
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        //1.更新本地交易记录状态 及关联微信支付订单号，回调时间，回调内容
        //1.1 从微信交易对象获取商户订单编号查询本地交易记录
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        String paymentStatus = paymentInfo.getPaymentStatus();
        if (paymentInfo != null && SystemConstant.PAYMENT_STATUS_UNPAID.equals(paymentStatus)) {
            //1.2 判断本地交易记录状态，如果是未支付，则更新状态（已支付）、微信订单号、回调时间、回调内容
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(transaction.toString());
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            this.updateById(paymentInfo);

            //支付类型：1301-订单 1302-充值
            String paymentType = paymentInfo.getPaymentType();
            //2.处理支付类型为订单的业务
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //2.1 远程调用订单服务 处理订单及虚拟物品发货业务
                Result result = orderFeignClient.orderPaySuccess(orderNo);
                //2.2 判断响应业务状态码
                if (!result.getCode().equals(200)) {
                    throw new RuntimeException("订单处理失败");
                }
            }
            //3.处理支付类型为充值的业务
            if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                //3.1 远程调用账户服务 处理充值业务
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
                //3.2 判断响应业务状态码
                if (!result.getCode().equals(200)) {
                    throw new RuntimeException("充值失败");
                }
            }
        }
    }
}
